
class StackStateMachine:
    def __init__(self):
        self.stack = []
        self.MAX_INT = (1 << 20) - 1
        self._append = self.stack.append
        self._pop = self.stack.pop
        self._len = lambda: len(self.stack)  # 修正_len的定义（原代码可能错误）

    def calculate_result(self) -> int:
        return self.stack[-1] if self._len() > 0 else -1

    def process(self, operation: str) -> bool:
        if operation[0] in '0123456789':
            return self._process_number(operation)
        elif operation == "POP":
            return self._process_pop()
        elif operation == "DUP":
            return self._process_dup()
        elif operation == "+":
            return self._process_add()
        elif operation == "-":
            return self._process_sub()
        else:
            return False

    def _process_number(self, num: str) -> bool:
        number = int(num)
        if number > self.MAX_INT:
            return False
        self._append(number)
        return True

    def _process_pop(self) -> bool:
        if self._len() < 1:
            return False
        self._pop()
        return True

    def _process_dup(self) -> bool:
        if self._len() < 1:
            return False
        self._append(self.stack[-1])
        return True

    def _process_add(self) -> bool:
        if self._len() < 2:
            return False
        a = self._pop()
        b = self._pop()
        res = a + b
        if res > self.MAX_INT:
            return False
        self._append(res)
        return True

    def _process_sub(self) -> bool:
        if self._len() < 2:
            return False
        # 修正弹出顺序：先弹被减数，后弹减数
        minuend = self._pop()
        subtrahend = self._pop()
        diff_val = minuend - subtrahend
        if diff_val < 0:
            return False
        self._append(diff_val)
        return True

def solution(S):
    machine = StackStateMachine()
    for op in S.split():
        if not machine.process(op):
            return -1
    # 确保方法名正确
    return machine.calculate_result()

# 测试样例
print(solution("4 5 6 - 7 +"))  # 正确结果应为 8